package com.gateway.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import com.gateway.entity.User;

public class IUserDaoImpl extends BaseDao implements IUserDao {

  private Logger log=Logger.getLogger(this.getClass());

  public int add(User user) {
    if(null != selectByName(user.getUsername())) {
      log.debug("username[" + user.getUsername() + "] exist");
      return 0;
    }
    SqlSession session=openSession();
    try {
      return session.insert("UserMapper.add", user);
    } finally {
      session.close();
    }
  }

  public void delete(int id) {
    SqlSession session=openSession();
    try {
      session.delete("UserMapper.delete", id);
    } finally {
      session.close();
    }
  }

  public List<User> selectAll() {
    SqlSession session=openSession();
    try {
      return session.selectList("UserMapper.selectAll");
    } finally {
      session.close();
    }
  }

  public User selectById(int id) {
    SqlSession session=openSession();
    try {
      return session.selectOne("UserMapper.selectById", id);
    } finally {
      session.close();
    }
  }

  public void update(User user) {
    SqlSession session=openSession();
    try {
      session.update("UserMapper.update", user);
    } finally {
      session.close();
    }
  }

  public User login(String username, String password) {
    SqlSession session=openSession();
    try {
      Map<String, Object> params=new HashMap<String, Object>();
      params.put("username", username);
      params.put("password", password);
      User u=session.selectOne("UserMapper.login", params);
      return null != u ? u : null;
    } finally {
      session.close();
    }
  }

  public User selectByName(String username) {
    SqlSession session=openSession();
    try {
      return session.selectOne("UserMapper.selectByName", username);
    } finally {
      session.close();
    }
  }
}
